import subprocess
import re
import requests
import xml.etree.ElementTree as ET
import platform
import logging
import sys
import time

# 配置日志
logging.basicConfig(level=logging.INFO,
                    format='%(asctime)s - %(levelname)s - %(message)s',
                    handlers=[logging.StreamHandler(sys.stdout)])

# 定义变量
api_mode = 'dynadot'  # 或 'duckdns'，根据需要选择API模式

# DuckDNS设置
subdomain_duckdns = 'fanderchan'
token_duckdns = 'd782206b-283f-4c34-92xxxxxxxxxxxx'

# Dynadot设置
domain_dynadot = 'xxxxxx'  # 域名（Dynadot专用）
subdomain_dynadot = '181'  # 子域名
token_dynadot = 'a7c8r6Ci9L6i8e7e6i6D7xxxxxxxxxxx'  # Dynadot API密钥

# 获取操作系统类型
os_type = platform.system()
logging.info(f"platform.system: {os_type}")

ipv6 = ""

if os_type == "Windows":
    try:
        output = subprocess.check_output('ipconfig', encoding='gbk')
        ipv6_pattern = r'以太网适配器 以太网:[\s\S]*?IPv6 地址 . . . . . . . . . . . . : ([\da-fA-F:]+)'
        match = re.search(ipv6_pattern, output)
        if match:
            ipv6 = match.group(1)
            logging.info(f"Found IPv6: {ipv6}")
        else:
            logging.warning("IPv6 address not found. Please ensure your network is connected to IPv6.")
    except Exception as e:
        logging.error(f"Failed to execute ipconfig: {e}")

elif os_type == "Linux":
    net_card = "ens33"  # Ensure this matches your actual network interface
    command = f"ip -6 addr show {net_card} | grep 'inet6' | awk '{{print $2}}' | cut -d'/' -f1"
    try:
        ipv6 = subprocess.getoutput(command).splitlines()[0]
        if ipv6:
            logging.info(f"Found IPv6: {ipv6}")
        else:
            logging.warning("IPv6 address not found. Please ensure your network is connected to IPv6.")
    except Exception as e:
        logging.error(f"Failed to execute command: {e}")

if not ipv6:
    exit()

if api_mode == 'dynadot':
    logging.info("Updating Dynadot...")
    query_url = f'https://api.dynadot.com/api3.xml?key={token_dynadot}&command=get_dns&domain={domain_dynadot}'
    logging.info(f"Constructed Dynadot query URL: {query_url}")

    # 重试逻辑开始
    for attempt in range(2):  # 尝试最多两次
        try:
            response = requests.get(query_url)
            logging.info(f"Queried Dynadot DNS settings. Response code: {response.status_code}")
            response_content_str = response.content.decode('utf-8')
            logging.info(f"Dynadot API response content: {response_content_str}")
            root = ET.fromstring(response.content)
            response_code = root.find('.//ResponseCode').text
            if response_code == '0':  # 成功获取响应
                break  # 退出循环进行后续处理
            else:  # 如果响应码不是 '0'，说明有错误
                error_message = root.find('.//Error').text if root.find('.//Error') is not None else 'Unknown error'
                logging.warning(f"Dynadot API returned an error: {error_message}")
                if attempt == 0:  # 如果是第一次尝试失败
                    logging.info("Waiting 5 seconds before retrying...")
                    time.sleep(5)  # 等待 5 秒再次尝试
                else:  # 如果第二次尝试仍然失败
                    logging.error("DNS query failed, terminating script execution.")
                    exit()
        except Exception as e:
            logging.error(f"Error communicating with Dynadot API: {e}")
            exit()

    # 在成功获取响应后的处理
    record_exists = False

    for sub in root.findall('.//SubDomainRecord'):
        subhost = sub.find('Subhost').text
        record_type = sub.find('RecordType').text
        value = sub.find('Value').text
        if subhost == subdomain_dynadot and record_type == 'AAAA' and value == ipv6:
            logging.info("DNS record is already up to date on Dynadot. No need to update.")
            record_exists = True
            break

    if not record_exists:
        logging.info("No existing DNS record found. Adding new record on Dynadot.")
        update_url = f"https://api.dynadot.com/api3.xml?key={token_dynadot}&command=set_dns2&domain={domain_dynadot}&subdomain0={subdomain_dynadot}&sub_record_type0=aaaa&sub_record0={ipv6}&add_dns_to_current_setting=1"
        logging.info(f"Constructed Dynadot update URL: {update_url}")
        try:
            update_response = requests.get(update_url)
            logging.info(f"Sent update request to Dynadot. Response code: {update_response.status_code}")
            update_root = ET.fromstring(update_response.content)
            if update_root.find('.//SuccessCode').text == '0':
                logging.info("IPv6 address added successfully on Dynadot.")
            else:
                response_error = update_root.find('.//Error')
                error_text = response_error.text if response_error is not None else 'Unknown error'
                logging.warning(f"Failed to add IPv6 address on Dynadot. Error: {error_text}")
        except Exception as e:
            logging.error(f"Error communicating with Dynadot API: {e}")

